import json
import os
from password_utils import encrypt_password, is_encrypted

class Config:
    """配置类，用于管理应用程序的各种配置参数"""
    
    def __init__(self, config_file="app_config.json"):
        self.config_file = config_file
        # 注意：数据库密码支持明文和密文两种方式；默认使用密文形式的 "Liu123456"
        self.default_config = {
            "database": {
                "host": "rm-bp1kz957499m2o7lczo.mysql.rds.aliyuncs.com",
                "port": 3306,
                "database": "weiliu99",
                "username": "weiliu66",
                # 默认密码使用密文形式（支持明文/密文双模式读取）
                "password": "ENC:TGl1MTIzNDU2"
            },
            "delay": {
                "category_delay": 3,      # 类目间延迟（秒）
                "subcategory_delay": 2,   # 子类目间延迟（秒）
                "goods_delay": 1,         # 商品处理延迟（秒）
                "video_request_delay": 5, # 视频请求延迟（秒）
                "retry_delay": 5          # 重试延迟（秒）
            },
            "retry": {
                "max_retries": 3,         # 最大重试次数
                "retry_delay": 5          # 重试延迟（秒）
            },
            "download": {
                "default_path": "ks-download",
                "max_threads": 3,
"enable_subcategory": False,
                "auto": {
"enabled": False,
                    "interval_minutes": 0
                }
            },
            "crawl": {
                "selected_categories": [],  # 选中的抓取类目
                "date_range": "30d",       # 日期范围
                "rank_type": "video",      # 榜单类型
                "cleanup_option": "清除24小时之前的数据",  # 数据清除选项
                "auto": {
"enabled": False,
                    "interval_minutes": 0
                }
            },
            "stats": {
                "crawl": {
                    "date": "",               # 抓取统计日期（YYYYMMDD格式）
                    "goods": 0,               # 今日累计抓取商品数
                    "videos": 0               # 今日累计抓取视频URL数
                },
                "download": {
                    "date": "",               # 下载统计日期（YYYYMMDD格式）
                    "videos": 0               # 今日累计下载视频数
                }
            },
            "network": {
                "proxy_enabled": False,
                "socks5_host": "127.0.0.1",
                "socks5_port": 1086
            }
        }
        self.config = self.load_config()
        
    def load_config(self):
        """加载配置文件"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    # 合并默认配置和文件配置
                    merged_config = self.default_config.copy()
                    for key, value in config.items():
                        if isinstance(value, dict) and key in merged_config:
                            merged_config[key].update(value)
                        else:
                            merged_config[key] = value
                    
                    # 确保数据库密码存在；如未配置，则使用 "Liu123456" 的密文
                    db_cfg = merged_config.get("database", {})
                    if "password" not in db_cfg or not db_cfg.get("password"):
                        db_cfg["password"] = encrypt_password("Liu123456")
                        merged_config["database"] = db_cfg
                        self.save_config(merged_config)
                    
                    # 兼容旧版本：自动添加缺失的stats配置
                    if "stats" not in merged_config:
                        merged_config["stats"] = self.default_config["stats"]
                        self.save_config(merged_config)  # 立即保存更新后的配置
                    else:
                        # 确保stats下的子项完整
                        stats_updated = False
                        if "crawl" not in merged_config["stats"]:
                            merged_config["stats"]["crawl"] = self.default_config["stats"]["crawl"]
                            stats_updated = True
                        else:
                            # 确保crawl下有date字段
                            if "date" not in merged_config["stats"]["crawl"]:
                                merged_config["stats"]["crawl"]["date"] = ""
                                stats_updated = True
                            if "goods" not in merged_config["stats"]["crawl"]:
                                merged_config["stats"]["crawl"]["goods"] = 0
                                stats_updated = True
                            if "videos" not in merged_config["stats"]["crawl"]:
                                merged_config["stats"]["crawl"]["videos"] = 0
                                stats_updated = True
                        
                        if "download" not in merged_config["stats"]:
                            merged_config["stats"]["download"] = self.default_config["stats"]["download"]
                            stats_updated = True
                        else:
                            # 确保download下有date字段
                            if "date" not in merged_config["stats"]["download"]:
                                merged_config["stats"]["download"]["date"] = ""
                                stats_updated = True
                            if "videos" not in merged_config["stats"]["download"]:
                                merged_config["stats"]["download"]["videos"] = 0
                                stats_updated = True
                        
                        # 如果有更新，保存配置文件
                        if stats_updated:
                            self.save_config(merged_config)
                    
                    return merged_config
            except Exception as e:
                print(f"加载配置文件出错: {e}")
                return self.default_config
        else:
            # 如果配置文件不存在，创建默认配置文件
            self.save_config(self.default_config)
            return self.default_config
            
    def save_config(self, config=None):
        """保存配置到文件"""
        if config is None:
            config = self.config
            
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=4)
        except Exception as e:
            print(f"保存配置文件出错: {e}")
            
    def get(self, key, default=None):
        """获取配置项"""
        keys = key.split('.')
        value = self.config
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        return value
        
    def set(self, key, value):
        """设置配置项"""
        keys = key.split('.')
        config = self.config
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        config[keys[-1]] = value
        self.save_config()

# 全局配置实例
config = Config()